0

I'm trying to convert a number to a string to use as a key. But the problem is, when I the newly converted string, it still acts like a number. Is there a right way of doing this?

JAVASCRIPT

var arr = [];

var num = 3;

var key = String(''+num); //Convert number into string

//var key = ''  +num;         //Tried this
//var key = num.toString(); //Tried this also

array[key] = true;

console.log(arr); //Returns [, , true]
console.log(arr.length); //Returns 3

Basically, I want it to return just:

console.log(arr); //Return [true]
console.log(arr.length); //Return 1
6
  • 2
    and what do you want? please add the result as well. Commented Jan 28, 2017 at 16:54
  • 1
    JavaScript turns any expression you use with the [ ] operator into a string. You don't have to do anything at all. arr[3] is the same as arr["3"]. Commented Jan 28, 2017 at 16:55
  • 2
    how do you map 3 to index 0? Commented Jan 28, 2017 at 16:56
  • 1
    @tery.blargh OK well the answer is you cannot do that. You could use a plain object instead of an array however. Commented Jan 28, 2017 at 16:56
  • 1
    I'm not sure what you want to achieve, but arrays don't have "keys", probably you want to use and Object instead? Commented Jan 28, 2017 at 16:56

1 Answer 1

3

What you're looking for is an Object ({}) not an Array ([]). Use this instead:

var obj = {};
var key = 3;
obj[key] = true; // no need to convert the key to string

EXAMPLE:

var obj = {};
var key = 3;
obj[key] = true;

console.log(obj);

Sign up to request clarification or add additional context in comments.

2 Comments

so you are looking for an object, instead of an array. plain object have no (built in) length property.
They do after Object.keys() :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.