我有一个像这样的数组
0: "City1"
1: {name="sds", age="asd",....}
2: {name="sweds", age="accxsd",....}
3: {name="sdqws", age="asssd",....}
4: "City2"
... and many more
所以我需要获取index[0]
和index[4]
之间的元素,
我能够使用 typeof
检查 string
和 object
for(i=0; i<=arr.length; i++){
if(typeof arr[i] == 'string'){
... // need to find next element eith type string
}
}
有没有办法找到数组中值为字符串的下一个元素,这样我就可以得到它们之间的元素。
最佳答案
您可以使用 reduce
函数来使用此替代方法。
此方法构建一个对象,将对象分组到一个数组中,其中包含找到的字符串值。
var array = [ "City1", {name:"sds", age:"asd"}, {name:"sweds", age:"accxsd"}, {name:"sdqws", age:"asssd"}, "City2", {name:"sds2", age:"asd2"}, {name:"sweds2", age:"accxsd2"}, {name:"sdqws2", age:"asssd2"}];
var result = array.reduce((a, c) => {
if (typeof c === 'string') {
a[c] = [];
a.current = c;
} else if (a.current !== "") {
a[a.current].push(c);
}
return a;
}, {current: ""});
delete result.current;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
How can I adjust to a particular String value, like if my input id 'city3', I need to get all elements between 'city3' and its next string value
上述方法通过之前找到的字符串元素对元素进行分组,因此可以直接访问所需的目标City3
var array = [ "City1", {name:"sds", age:"asd"}, {name:"sweds", age:"accxsd"}, {name:"sdqws", age:"asssd"}, "City3", {name:"sds3", age:"asd3"}, {name:"sweds3", age:"accxsd3"}, {name:"sdqws3", age:"asssd3"}, "City4", {name:"sds4", age:"asd4"}, {name:"sweds4", age:"accxsd4"}, {name:"sdqws4", age:"asssd"}];
var result = array.reduce((a, c) => {
if (typeof c === 'string') {
a[c] = [];
a.current = c;
} else if (a.current !== "") {
a[a.current].push(c);
}
return a;
}, {
current: ""
});
delete result.current;
var target = "City3";
// Now you have a direct access to find the desired target.
console.log(result[target]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在数组 javascript 之间获取特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450155/