简体   繁体   English

Javascript:如何区分对象文字

[英]Javascript: How to differentiate object literals

I want to know how we can differentiate between object literals and json objects, with other objects such as Date, Function, etc. 我想知道如何区分对象文字和json对象,以及其他对象,例如Date,Function等。

Since the typeof operator as well as the instanceof Object operator returns true for both of the object, is there a way to differentiate between them? 由于typeof运算符以及instanceof Object运算符对这两个对象都返回true,是否有办法区分它们?

PS: I don't want to do it by reverse exclusion of Date and Function, since it won't handle cases other than Date or function. PS:我不希望通过反向排除Date和Function来做到这一点,因为它不能处理Date或Function以外的情况。

Everything non-primitive is an object, but not everything that's an object is also a Date, or a function. 所有非原始的东西都是对象,但并非所有对象的东西都是日期或函数。 Instead of checking instanceof Object , check instanceof Date , or instanceof Function : 而不是检查instanceof Object ,而是检查instanceof Dateinstanceof Function

 const obj = {}; const date = new Date(); const fn = () => 'foo'; console.log(date instanceof Date); console.log(obj instanceof Date); console.log(fn instanceof Function); console.log(obj instanceof Function); 

and json objects 和json对象

Keep in mind that there's no such thing as a "JSON Object" 请记住, 没有“ JSON对象”之类的东西

If you just want to make a copy of a Javascript object (including arrays, since they're objects too), but excluding non-valid JSON objects (like Date s, Function s, etc.), one of the simplest way is to convert the Javascript object to JSON string, and then re-parse it: 如果您只想复制一个Javascript对象(包括数组,因为它们也是对象),但要排除无效的JSON对象(例如DateFunction等等),则最简单的方法之一是将Javascript对象转换为JSON字符串,然后重新解析:

function deepCopy(input){
  const json = JSON.stringify(input);
  return JSON.parse(json);
}

const obj1 = { "hello": "world" };
const obj2 = deepCopy(obj1);

// obj1 and obj2 are two distinct objects
obj1["hello"] = "bye";
console.log( obj2["hello"] ); // world

// this works for arrays too
const a = [1, 2, [3, 4]];
const b = deepCopy(a);

NOTE: be aware that, even if it works, it is not the best solution (especially because of performance issues). 注意:请注意,即使可行,它也不是最佳解决方案(特别是由于性能问题)。

You can also write a function, whose purpose is to analyze a Javascript object in order to see if it can be a valid JSON object (ie a plain Object with only primitives and arrays in it). 您还可以编写一个函数,其目的是分析Javascript对象,以查看它是否可以是有效的JSON对象(即,其中仅包含基元和数组的纯Object)。 This way, you can differentiate from Date s and other "complex" objects. 这样,您就可以区别于Date和其他“复杂”对象。 Take a look at JSON specification (or Wikipedia) in order to know which data types JSON supports. 查看JSON规范(或Wikipedia),以了解JSON支持哪些数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM