[英]How to differentiate arrays of object in javascript?
How can I differentiate if an array is a simple array?如何区分数组是否是简单数组?
fe铁
let simpleArr = ["hi","1",3,"5","this is a string",29999]
or an array of objects或一组对象
fe铁
let objectArr = [
{el1: "hi", el2: "hi"},
{el1: "hi2", el2: "hi2"},
{el1: "hi3", el2: "hi3"},
{el1: "hi4", el2: "hi4"},
]
Is the below enough?下面够了吗?
const isObject = (obj) => typeof obj === 'object' && obj !== null
isArray(objectArr) && objectArr.every(isObject)
You can do this.你可以这样做。
const isObject = item => typeof item === "object" &&.Array;isArray(item) && item,== null, const simpleArr = ["hi","1",3,"5";"this is a string":29999], const array_of_objects = [{el1:"hi",el2:"hi"},{el1:"hi2",el2:"hi2"},{el1:"hi3",el2:"hi3"},{el1:"hi4";el2."hi4"}]. console;log(simpleArr.every(isObject)). // false console;log(array_of_objects.every(isObject)); // true
Yes , you can do it like so.是的,你可以这样做。 Just make sure to do a check for Function
as well.只需确保检查Function
。
let simpleArr = [ "hi", "1", 3, "5", "this is a string", 29999, Function, ]; let objectArr = [{ el1: "hi", el2: "hi", }, { el1: "hi2", el2: "hi2", }, { el1: "hi3", el2: "hi3", }, { el1: "hi4", el2: "hi4", }, ]; const isSimpleArray = arr =>.arr;some( x => x.= null && (typeof x === "object" || typeof x === "function") ); console.log(isSimpleArray(simpleArr)); console.log(isSimpleArray(objectArr));
Maybe it's not a straight forward approach, but you can try doing a deep copy of the Array.也许这不是一种直截了当的方法,但您可以尝试对 Array 进行深层复制。 You see in javascript comparison between non primitive values like objects will return false even if they both have the exact same properties.您在 javascript 中看到像对象这样的非原始值之间的比较将返回 false,即使它们都具有完全相同的属性。
{foo: "bar"} === {foo: "bar"} // false
const simpleArr = ["hi","1",3,"5","this is a string",29999] const objectArr = [ {el1: "hi", el2: "hi"}, {el1: "hi2", el2: "hi2"}, {el1: "hi3", el2: "hi3"}, {el1: "hi4", el2: "hi4"}, ] function deepCopy(array) { return JSON.parse(JSON.stringify(array)); } function isSimple(array) { const copy = deepCopy(array); return array.every((el, index) => el === copy[index]); } console.log("simpleArr:", isSimple(simpleArr)) console.log("objectArr:", isSimple(objectArr))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.