【问题标题】:Why is this showing both array and object like behaviour为什么这会同时显示数组和对象的行为
【发布时间】:2018-12-14 14:42:08
【问题描述】:

请考虑下面的 JavaScript 代码。

var obj = /e/.exec("The best things in life are free!");
var k = "";
var x;
for (x in obj) {
  k = k + " " + obj[x] + " " + x + "<br>";
}
document.getElementById("demo").innerHTML = (obj instanceof Array) + " " + obj[0] + " " + obj[1] + " " + obj.index + "<br>" + k;
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>

给出一个输出

JavaScript Regular Expressions
true e undefined 2
e 0
2 index
The best things in life are free! input
undefined groups  

现在在上面的代码中,我使用了obj[0]obj[1](which are array only notations), and alsoobj.index`(它不应该适用于数组)。

现在我真的很困惑 obj 到底是什么......

【问题讨论】:

    标签: javascript arrays regex


    【解决方案1】:

    现在在上面的代码中我使用了 obj[0] , obj1 (它们是仅数组符号)

    不,他们不是。例如:

    const obj = {answer: 42, 42: "is the answer"};
    const str = "answer";
    console.log(obj[str]); // 42
    console.log(obj[42]);  // is the answer

    .... 还有 obj.index (它不应该用于数组)

    是的,他们应该这样做。 :-)

    javaScript 中的标准数组根本不是真正的数组。它们只是以下对象:

    • Array.prototype继承。
    • 对名为 length 的属性具有特殊行为。
    • 对于名称与array index 的定义匹配的属性具有特殊行为(当转换为数字n 时,其范围为0 32 - 1)。这些是对应于数组条目的属性。我们通常不带引号 (myArray[0]) 编写它们,但正式它们是字符串。
    • 拥有自己的文字形式 ([])。

    由于它们是对象,因此它们也可以具有属性:

    const a = [1, 2, 3];
    a.answer = 42;
    console.log(a.answer); // 42

    JavaScript 本身在几个地方(但不是很多)利用了这一事实,包括您发现的 RegExp.prototype.exec 函数。另一个地方是传递给tag function 的第一个参数,它具有来自模板的字符串段的条目和带有这些段的原始版本的raw 属性。

    更多关于我贫血的小博客:A Myth of Arrays

    【讨论】:

    • 那么如何为数组指定属性
    • @AyushMangal - 我不明白你的意思是什么?
    • JS 中的数组与 PHP 中的数组不同,它们不是关联的,而是被索引的
    • @AyushMangal - 数组的文字表示法只允许您指定数组条目,而不是其他属性。因此,您在事后添加它们,就像我在答案中的最后一个示例中所做的那样(我可能在您写上面的第一条评论时添加了它们)。
    • @T.J.Crowder 是的,那是在我写作的时候......感谢您的帮助
    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2015-08-17
    相关资源
    最近更新 更多