首页 > 解决方案 > 如何使用Javascript在数组中查找json对象的索引

问题描述

我有一个如下所示的数组

let formulaArray = ["(", "(", "(", "2", "+", "3", ")", "*", "3", ")", "+", "(", "12", "/",{}]
 }

数组中的 json 对象可以在任何索引处。现在,我想找到 json 对象的索引,我该怎么做?

标签: javascript

解决方案


使用.forEach()然后用typeof运算符检查对象,如果为真,则将其推送到数组

var formulaArray = ["(",{}, "(", "(", "2", "+", "3", ")", "*", "3", ")", "+", "(", "12", "/",null,{}]
var objectIndex = [];
formulaArray && formulaArray.forEach(function(item, index){
    typeof item==='object' && item!==null && 
objectIndex.push(index);
})
console.log(objectIndex)


推荐阅读