简体   繁体   English

如何在JavaScript中的2D数组中查找值

[英]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 这将返回0或ant其他整数

Also push is not making the format as expected, how shall I push key(my word) and its defalut value in the 2d array? 另外push没有按预期方式制作格式,如何在2d数组中推送key(我的单词)及其默认值?

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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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