简体   繁体   中英

How to find value in 2d array in javascript

this is my code

var text = input.split(" ");
var wordCount = new Array();
var i;
for(i=0; i<text.length; i++){
    if(wordCount.length==0){
        wordCount.push(text[i], 1);
    }
    var index= wordCount.indexOf(text[i]);

so now I have the index of the key and want to find a value corresponding to this key.

I can write a custom sequential method to get the value but is there a shortcut so that I can just say,

var value = wordCount.getValue(text[i]); and that will return 0 or ant other integer

Also push is not making the format as expected, how shall I push key(my word) and its defalut value in the 2d array?

Store the corresponding index also with value in the array like this

for(i=0; i < text.length; i++){
if(wordCount.length==0){
    wordCount[i] = text[i];
}

so while retriving value you can do

for(var key in wordCount)
{
  alert("key " + key + " has value " + wordCount[key]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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