Thursday 30 November 2017

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

itemprop="text">












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



var array =
{};

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


When I try to run
the rel="noreferrer">splice method on the
array I get a TypeError: array.splice is not a
function
. My intent is to remove the
an_object "key" and all its content from the
array
variable.




How can I make
that?



/>

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



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

itemprop="text">
class="normal">Answer





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



var
myObject = {};

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


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




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]"]


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...