Javascript数组以不同的方式运行 [英] Javascript Array behaving in a different manner

查看:64
本文介绍了Javascript数组以不同的方式运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我附上了我的Firefox控制台的屏幕截图,并想知道为什么数组在javascript中的行为如此。

Hi I am attaching a screenshot of my Firefox Console and would like to know why does array behave like this in javascript.

我试图了解... in和for ... in js但遇到了这个问题。我现在明白,因为...正在打印只是键,而...正在打印值部分。但我不明白为什么数组首先采用键值对?

I was trying to understand for...in and for...of in js but came across this problem. I now understand that for...in is printing just the key while for...of is printing the value part. But i don't understand why did array a take key value pair in the first place?

我想因为Array也是一个对象它可以采取一个键:值对作为输入但是当我在console.log(a)时为什么它不打印foo:bar,即使打印[foo]打印bar。是否有一些我错过并且无法理解的概念?

I suppose as Array is also an Object it can take A key:value pair as input but then when i console.log(a) then why does it not print foo: bar, even though printing a["foo" ] prints "bar". Is there some concept that i'm missing out and unable to understand?

但Chrome浏览器显示如下:

However Chrome browser displays as follow:

在这种情况下,打印数组a给了我[1,2,3,foo:bar ]如果我定义

In this case printing array a is giving me [1,2,3,foo: "bar"] as output however if i define

var b=[1,2,3,foo: "bar"] 

它给了我意想不到的令牌。为什么会这样?

it gives me unexpected token . Why is it so?

推荐答案

这是一个很好的问题:-)粗略地说,数组是一个<$的对象c $ c> length property,一组标签从 0 length - 1 ,以及一些特定功能。我们几乎可以说 a = [1,2,3] 是 的快捷方式:

Here is a good question :-) Roughly speaking, an array is an object with a length property, a set of properties labeled from 0 to length - 1, and a couple of specific features. We could almost say that a = [1, 2, 3] is a shortcut for :

a = { 0: 1, 1: 2, 2: 3, length: 3 }

实际上,您可以使用普通对象轻松模拟数组。

In fact, you can easily simulate an array using a plain object.

对象是键值对的集合,如字典。密钥可以是任意字符串,值可以是任何类型的数据。在JavaScript中,几乎所有东西都是一个对象。数组是一个对象,一个函数是一个对象,甚至像数字和字符串这样的原子数据也可以像对象一样被操纵,实际上,JavaScript秘密地创建了一个对象以包装原子数据。

An object is a collection of key-value pairs, like a dictionary. A key can be any arbitrary string, and a value can be any type of data. In JavaScript, almost everything is an object. An array is an object, a function is an object, even atomic data like numbers and strings can be manipulated like an object, indeed, JavaScript secretly creates an object in order to wrap the atomic data.

有两种方法可以创建对象。通常你会看到基于括号的文字符号( {} [] )或 new 关键字。字面符号只是语法糖,实际上,您的计算机在两种情况下都执行完全相同的指令序列。换句话说, o = {} o = new Object()和<$ c $相同c> a = [] 与相同a = new Array()

There are a couple of ways to create an object. Often you'll see either the literal notation based on brackets ({} and []) or the new keyword. The literal notation is just syntactic sugar, in fact, your computer executes the exact same sequence of instructions in both cases. In other words, o = {} is the same as o = new Object(), and a = [] is the same as a = new Array().

是的,当你写 a = [] 时,你隐含地创建了一个 Array 类的实例,这个是使数组成为特殊对象的原因:-)如上所述,数组是具有附加功能的对象,这些功能继承自 Array 类。 indexOf 方法就是其中之一(在控制台中键入 Array.prototype 以列出所有内容) :

Yes, when you write a = [], you are implicitely creating an instance of the Array class, this is what makes an array a special object :-) As stated above, an array is an object with additional features, and these features are inherited from the Array class. The indexOf method is one of them (type Array.prototype in a console to list them all) :

var a = ["a", "b", "c"];
a.indexOf("b"); // 1

直到最近,只要你没有调用数组来自对象本身的特定方法,您可以通过向普通对象添加 length 属性并将其用作数组来轻松欺骗JavaScript。 JQuery利用了这种技术 : http://api.jquery.com/Types/#ArrayLikeObject

Until recently, as long as you didn't call Array specific methods from the object itself, you could easily cheat on JavaScript by adding a length property to a plain object and use it as an array. JQuery takes advantage of this technique : http://api.jquery.com/Types/#ArrayLikeObject.

var o = { length: 0 };
Array.prototype.push.call(o, "a", "b");
console.log(o, Array.prototype.slice.call(o));

今天这有点难以实现,例如,你必须实现一个迭代器才能在一个普通对象中使用 for ... of loop :

Today this is a little harder to achieve, for example, you have to implement an iterator to be able to use a plain object in a for ... of loop :

var o = {
  0: "a", 
  1: "b", 
  2: "c", 
  length: 3 
};

// o[Symbol.iterator] = Array.prototype[Symbol.iterator];
// works as well, but I want you to see there is no magic :-)

o[Symbol.iterator] = function() {
  return {
    i: 0,
    o: this,
    next: function() {
      var o = this.o;
      var i = this.i++;
      return {
        value: o[i],
        done: i === o.length
      }
    }
  };
};

for (var x of o) {
  console.log(x);
}

for (var x in o) {
  console.log(x, o[x]);
}

请注意JavaScript忽略了中的真实数组的 length 属性,用于......在循环中。在我的拙见中,这是一个值得怀疑的选择,最有可能导致坦率新手大脑中出现蓝屏...

Note that JavaScript ignores the length property of a true array in a for ... in loop. In my humble opinion this is a questionable choice that is most likely to cause a blue screen in the brain of the candid newbie...

var a = [1, 2, 3];
a["i'm"] = "your father";

console.log("length", a.length);
for (var k in a) {
  console.log(k, a[k]);
}

最后一句话,不要对Chrome控制台的输出感到困惑,它显示阵列的方式是谷歌开发者的随意选择。看,打印东西与编写源代码无关,确实,你有力量了!

Final word, don't get confused by the output of the Chrome's console, the way it displays arrays is an arbitrary choice of Google developers. Look, printing things has nothing to do with writing source code, indeed, you have the power !

printArray([1, 2, 3]);

function printArray(a) {
  console.log("[" 
  + a.join(", ") + ", "
  + "length: " + a.length 
  + "]");
}

进一步阅读 : https://stackoverflow.com/a/5048482/1636522

Further reading : https://stackoverflow.com/a/5048482/1636522.

这篇关于Javascript数组以不同的方式运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆