简体   繁体   English

javascript string.split(',')在应创建数组时生成对象

[英]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运算符结果

  • Undefined : "undefined" 未定义: “未定义”
  • Null : "object" Null: “对象”
  • Boolean : "boolean" 布尔值: “布尔值”
  • Number : "number" 编号: “编号”
  • String : "string" 字符串: “字符串”
  • Object (native and does not implement [[Call]]) : "object" 对象(本机,未实现[[Call]]): “对象”
  • Object (native or host and does implement [[Call]]) : "function" 对象(本机或主机,并且确实实现了[[Call]]): “功能”
  • Object (host and does not implement [[Call]]) : Implementation-defined except may not be "undefined", "boolean", "number", or "string". 对象(主机,未实现[[Call]]): 实现定义的对象,但不能为“ undefined”,“ boolean”,“ number”或“ string”。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM