Javascript 'var array = {}'时如何解决“TypeError: array.splice is not a function”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13525140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:17:21  来源:igfitidea点击:

How to solve the "TypeError: array.splice is not a function" when 'var array = {}'?

javascriptjqueryarrays

提问by user12882

Possible Duplicate:
How to remove a property from a javascript object
JavaScript Hashmap Equivalent

可能的重复:
如何从 javascript 对象JavaScript Hashmap 等效项中删除属性

I am using jQuery and I am handling a variable this way:

我正在使用 jQuery 并以这种方式处理变量:

var array = {};

array[an_object]      = something
array[another_object] = something_else
array[...]            = ...

When I try to run the splicemethod on the arrayI get a TypeError: array.splice is not a function. My intent is to remove the an_object"key" and all its content from the arrayvariable.

当我尝试运行该splice方法时,array我得到一个TypeError: array.splice is not a function. 我的意图是an_objectarray变量中删除“键”及其所有内容。

How can I make that?

我怎样才能做到这一点?



Note: When I run the console.log(array[an_object])(the same is valid for another_objectand all other objects) I get:

注意:当我运行console.log(array[an_object])(同样适用于another_object和所有其他对象)时,我得到:

[Object { label="str1",  value=1 }, Object { label="str2",  value=2 }, { label="strN",  value=N }]

采纳答案by Cerbrus

First of all, name your variables what they are. The name arrayyou're using, is misleading if you use it to create a object.

首先,为变量命名。array如果您使用它来创建对象,则您使用的名称会产生误导。

var myObject = {};

myObject[an_object]      = "xyz";
myObject[another_object] = "abc";

Now, you can delete the entry in the object with the deletestatement:

现在,您可以使用以下delete语句删除对象中的条目:

delete myObject[an_object]; // Returns true / false if the deletion is a success / failure
console.log(myObject[an_object]) // Returns undefined


Now, that said, this will not work like you'd expect. myObject[an_object]will contain "abc"
Don't use objects as keys. Use strings, instead.
This is because of the fact that any parameter entered in the []will be converted to string. So actually, you're entering myObject["[object Object]"]

现在,也就是说,这不会像您期望的那样工作。myObject[an_object]将包含 "abc"
不要使用对象作为键。改用字符串。
这是因为在 中输入的任何参数[]都将转换为字符串。所以实际上,你正在进入myObject["[object Object]"]

回答by Billy Moon

I am a little confused about the way you are building your object, because an_objectused as a key would have to be a string value for a key. Assuming you do so, this should work by deleting the undesired property of the object.

我对您构建对象的方式有些困惑,因为an_object用作键必须是键的字符串值。假设你这样做了,这应该通过删除对象的不需要的属性来工作。

var array = {};

array['an_object'] = "something"
array['another_object'] = "something_else"

delete(array.an_object)

console.log(array) // Object { another_object = "something_else" }


EDIT

编辑

As detailed in comments, if the issue is that objects are being used as keys for another object (in this case confusingly named array), then the problem is that an object is first converted to it's string representation to be used in the context of an object key. Therefore, all objects used as keys, will actually refer to one key called [object Object], and whichever object you use as a key will overwrite previous ones.

正如评论中详述的那样,如果问题是对象被用作另一个对象的键(在这种情况下命名混乱array),那么问题是对象首先被转换为其字符串表示以在对象的上下文中使用钥匙。因此,所有用作键的对象实际上都会引用一个名为 的键[object Object],并且您用作键的任何对象都将覆盖以前的对象。

In the example in the question...

在问题中的示例中...

array[an_object]      = something
array[another_object] = something_else
// array: Object { "[object Object]" = "something_else" }

回答by Pebbl

To achieve a Dictionary in simple JavaScript is rather tricky, you would need to create an entire constructor to handle this - or use a library that would handle this for you.

要在简单的 JavaScript 中实现 Dictionary 相当棘手,您需要创建一个完整的构造函数来处理这个问题——或者使用一个可以为您处理这个问题的库。

By Dictionary I am refering to an object/hash that can use objects as keys. You would need a constructor that would use multiple arrays (one for the key and one for the value) and that would keep them in-sync. You could mimic many of the typical array methods, but as I stated this would be quite a bit of code.

通过字典,我指的是可以使用对象作为键的对象/哈希。您将需要一个使用多个数组的构造函数(一个用于键,一个用于值)并使它们保持同步。您可以模仿许多典型的数组方法,但正如我所说,这将是相当多的代码。

As a simple alternative you can do the following:

作为一个简单的替代方案,您可以执行以下操作:

function pushToObject(obj, key, value){
  if( !key||!obj ) return false;
  if( !key[''] ) {
    pushToObject.index = pushToObject.index||[];
    key[''] = pushToObject.index.length;
    pushToObject.index.push(key);
  }
  obj[key['']] = value;
  return true;
}

function removeFromObject(obj, key){
  if( !isNaN(key) ) {
    var list = listKeyObjects(obj);
    var item = list[key];
    return removeFromObject(obj,item);
  }
  else if(key) {
    if( !key[''] ){
      return false;
    }
    return delete obj[key['']];
  }
  return false;
}

function listKeyObjects(obj){
  var a = [];
  for(var i in obj){
    a.push(pushToObject.index[i]);
  }
  return a;
}

usage

用法

var array = {}; /// it would be best to change the name of this object
var an_object = {}, another_object = {};

/// add your items to the array object, this handles giving each of your
/// objects used as a key a unique index property. This does mean the objects
/// you use `an_object`, `another_object` are modified.
pushToObject( array, an_object, 'something else' );
pushToObject( array, another_object, 'something other than else' );

console.log(array); /// {0:'something else',1:'something other than else'}

removeFromObject( array, an_object ); /// remove using an object as a key

console.log(array); /// {1:'something other than else'}

removeFromObject( array, 0 ); /// remove using an offset index

console.log(array); /// {}

after thoughts

经过思考

Obviously the better option is to create your own dedicated constructor for this, but you could improve the above with a bit more code so that it didn't modify the key objects. Instead whenever working with an object as a key you could scan the pushToObject.indexfor the offset of your key object. I chose to go for the version that modifies your key objects however as it should function faster than having to scan a list every time you make an array modification.

显然,更好的选择是为此创建您自己的专用构造函数,但您可以使用更多代码改进上述内容,以便它不会修改关键对象。相反,每当使用对象作为键时,您都可以扫描pushToObject.index键对象的偏移量。我选择了修改关键对象的版本,因为它应该比每次进行数组修改时都必须扫描列表更快。

get key function

获取键函数

The above code only shows you how to add and how to remove, it may also be a good idea on getting a particular key object from an offset:

上面的代码仅向您展示了如何添加和删除,从偏移量中获取特定键对象也可能是一个好主意:

function getKeyObjectAtIndex = function(obj, index){
  var list = listKeyObjects(obj);
  return list[index] ? list[index] : null;
}

console.log(array); /// {0:'something else',1:'something other than else'}

var key = getKeyObjectAtIndex(array, 1);

console.log(key === another_object) /// === TRUE

回答by djakapm

Maybe like this:

也许是这样的:

Fiddle

小提琴

var array = {};

var an_object = {};

var another_object = {};    

array[an_object] = 'something'

array[another_object] = 'something_else'

alert(array[an_object]);

array[an_object] = null;

alert(array[an_object]);

delete array[an_object]

alert(array[an_object]);

回答by Anmol Saraf

You cannot fire array method on objects. Your case you have created an object literal instead of an array, define it like var a = []OR var a = new Array();

您不能在对象上触发数组方法。你的情况你已经创建了一个对象文字而不是一个数组,像var a = []OR一样定义它var a = new Array();

Hope it helps !!

希望能帮助到你 !!