This time I will show you how to detect arrays in web development. What are the precautions for detecting arrays in web development? The following is a practical case, let's take a look.
One of the oldest cross-domain problems in JS is passing arrays back and forth between frames. Developers quickly discovered that instanceof Array did not always return the correct results in this scenario. As mentioned above, each frame has its own Array// 采用鸭式辨型的方法检测数组function isArray(value) { return typeof value.sort === "function"; }
function isArray(value) { return Object.prototype.toString.call(value) === "[object Array]"; }
string result in all browsers. For arrays, the returned string is "[object Array]", regardless of the frame in which the array instance was constructed. The solution given by Kangax quickly became popular and was adopted by most JSclass libraries.
This method is often very useful when identifying built-in objects, but please do not use this method for custom objects. For example, using this method with the built-in JSON object will return "[object JSON]". Since then, ECMAScript5 has officially introduced Array.isArray() into JS. The only purpose is to accurately detect whether a value is an array. Like Kangax's function, Array.isArray() can also detect values passed across frames, so many JS libraries currently implement this method similarly. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese websiteOther related articles!
Recommended reading:What are the event processing rules in web development
##Why do you need to avoid using global variables in web developmentThe above is the detailed content of How to detect arrays in web development. For more information, please follow other related articles on the PHP Chinese website!