[英]javascript string.split(',') makes object when it should make array
var _={};
_.bullets='1,2,3';
console.log(typeof bullets);
string 串
console.log(_.bullets);
var bullets=_.bullets.split(',');
console.log(bullets); //REF 1
["1", "2", "3"] [“ 1”,“ 2”,“ 3”]
console.log(typeof bullets);
object 宾语
Why is it not array? 为什么不是数组? I can't figure out what I am doing wrong here
我无法弄清楚我在做什么错
UPDATE 更新
console.log([1,2,3]);
console.log(bullets); //REF 1
[1, 2, 3] [1,2,3]
["1", "2", "3"] [“ 1”,“ 2”,“ 3”]
What is the difference (one is a string one is a number?) 有什么区别(一个是字符串,一个是数字?)
typeof
never returns 'array'
. typeof
从不返回'array'
。 For instances of Array
, it returns 'object'
: 对于
Array
实例,它返回'object'
:
Table 20 — typeof Operator Results 表20 — typeof运算符结果
Source: ECMAScript spec 来源: ECMAScript规范
Use Array.isArray(a)
or a instanceof Array
. 使用
Array.isArray(a)
或a instanceof Array
。
Arrays are objects, so typeof
returns object
. 数组是对象,所以
typeof
返回object
。
Technically typeof
fits for primitive types while instanceof
fits for reference types . 从技术上讲,
typeof
适合原始类型,而instanceof
适合引用类型 。
If you use typeof
for some reference types ( Array, Object ), it will return "object"
. 如果将
typeof
用作某些引用类型( Array,Object ),它将返回"object"
。 Function
is the third reference type ; Function
是第三参考类型 ; it behaves differently ( typeof
wise) as it will return "function"
when typeof new Function()
. 它表现不同(
typeof
明智的),因为它会返回"function"
时typeof new Function()
Based on your example you can deduce that string
is a primitive type in JavaScript as typeof "blabla" === string
(which returns true). 根据您的示例,您可以推断出
string
是JavaScript中的原始类型 ,其类型为typeof "blabla" === string
(返回true)。 Yes that's something curious if you come from a traditional strongly typed language such as Java or C#. 是的,如果您来自传统的强类型语言(例如Java或C#),那会很好奇。
typeof
returns 'object' when supplied array values. 当提供数组值时,
typeof
返回'object'。 To test for an array you can do something like this (from JavaScript the Good Parts ): 要测试数组,您可以执行以下操作(来自JavaScript的Good Parts ):
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.