javascript - 在数组 javascript 之间获取特定值?

标签 javascript arrays typeof

我有一个像这样的数组

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 检查 stringobject

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/

相关文章:

arrays - 使用 “+=” 运算符将一个数组连接到另一个可选值数组

arrays - 何时使用转置在 Julia 中绘制轮廓

javascript - 为什么 typeof + 不是 "function"javascript

JavaScript - 检查变量是否为数字 : typeof doesnt work, isNaN

javascript - 如何在 Javascript 中检索基数树中的所有数据/单词

javascript - 将对象数组发送到 GraphQL

javascript - 将 html(文本)转换为 jQuery 对象 : lost value

javascript - 在 typescript 中导入所有内容不起作用

c++ - If-else 基于正在使用的 typedef

javascript - 访问 jSON 文件中的子树