如果我有一个JavaScript对象,请说
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
Run Code Online (Sandbox Code Playgroud)
是否有内置或接受的最佳实践方法来获取此对象的长度?
我有这个包含键和值对数组的对象.
console.log(myObject);
[ 'askdasuni.com': '11111',
'capsfrom2011.com': '22222',
'defusionet.com': '33333' ]
Run Code Online (Sandbox Code Playgroud)
当我在我的应用程序中调用res.send(myObject)时,我得到以下内容:
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 2
< Date: Wed, 11 Mar 2015 18:15:41 GMT
< Connection: keep-alive
[]
Run Code Online (Sandbox Code Playgroud)
我希望它发送myObject的内容,而不仅仅是"[]".
如果我将代码更改为res.send('string'),我会得到以下内容:
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 6
< Date: Wed, 11 Mar 2015 18:21:09 GMT
< Connection: keep-alive
<
string
Run Code Online (Sandbox Code Playgroud) 我有一个像下面这样的javascript数组,里面有几个元素.当我尝试读取数组的长度时,我总是得到0作为长度.任何人都可以告诉我为什么会这样.
我的数组是这样的:
var pubs = new Array();
pubs['b41573bb'] =['Albx Swabian Alb Visitor Guide','','15.12.2007 09:32:52',['0afd894252c04e1d00257b6000667b25']];
pubs['6c21a507'] =['CaSH','','29.05.2013 14:03:35',['30500564d44749ff00257b7a004243e6']];
Run Code Online (Sandbox Code Playgroud) 见下面给出的情景
var x = [];
x['abc'] = "hello";
console.log(x.length); //returns 0
var x = [1,2];
x['abc'] = "hello";
console.log(x.length); //returns 2
Run Code Online (Sandbox Code Playgroud)
这背后的任何原因或我错过了什么?
我想将两个常规数组绑定到一个关联数组中.第一个的值是键,第二个的值是元素.
var array1=new Array("key1","Key2","Key3");
var array2=new Array("Value1","Value2","Value3");
var associative_array=new Array();
for(var i=0;i<3;i++){
associative_array[array1[i]]=array2[i];
}
Run Code Online (Sandbox Code Playgroud)
但是当我试图获得新的关联数组的长度时,我注意到它是空的:
alert(associative_array.length);//always 0
Run Code Online (Sandbox Code Playgroud)
我做错了什么?Thanx提前.
正如我们已经知道的,数组和对象之间的区别之一是:
“如果你想提供特定的键,唯一的选择是一个对象。如果你不关心键,那就是一个数组”(在这里阅读更多)
此外,根据MDN 的文档:
数组不能使用字符串作为元素索引(如在关联数组中),但必须使用整数
然而,令我惊讶的是:
> var array = ["hello"]; // Key is numeric index
> array["hi"] = "weird"; // Key is string
content structure looks like: ["hello", hi: "weird"]
Run Code Online (Sandbox Code Playgroud)
数组的内容结构看起来很奇怪。更重要的是,当我检查它返回的数组类型时true
Array.isArray(array) // true
Run Code Online (Sandbox Code Playgroud)
问题: