如何在特定索引-Javascript中添加数组中的项

时间:2017-12-22 20:04:33

标签: javascript arrays

我想从数组的索引1插入一个元素:

 render() {
  if (some condition) {
      let rules = [{label:"a"},{label:"b"},{label:"c"},{label:"d"}];
      let data = [];
      rules.forEach((rule) => {

          data.push(
            <div>
              {//some condition to true  &&
                <label>OR</label>}  //this OR should be added only from the 1st index of the array

                <ComboBox
                  placeholder= "Select a token ..."
                  value={someval}
                  listItems={list} />
            </div>)

      });


  return data;
}

}

上述内容将针对所有“真实”条件进行推送,但我需要仅从数组的索引1的开头推送另一个元素。简而言之,只有数组中的第一个元素应该具有此元素。类似的东西:

if (some condition)
 {
   data.push(
       <span>Test</span><div><span>A</span></div>
)
}

最后,应该看起来像:https://jsfiddle.net/w42hke3h/

怎么办呢?有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

使用unshift。它的工作方式与push类似,但将元素添加到数组的前面。

let rules = [{label:"a"},{label:"b"},{label:"c"},{label:"d"}];
let data = [];

rules.forEach(() => {
   if (some condition) {
     data.unshift(...);
   }   
)};