简体   繁体   English

JavaScript-转换对象或数组的值的最佳方法

[英]javascript - best way to convert values of object or array

So I have a bunch of values I need to convert to new values. 因此,我有一堆需要转换为新值的值。 Basically with a legend. 基本上带有传说。 It'll make sense in a second. 一秒钟就会有意义。 So far, I've been using associative arrays, or in the context of javascript, objects as my legend. 到目前为止,我一直在使用关联数组,或者在javascript上下文中使用对象作为我的图例。

My use is applicable to individual strings, arrays as I have blow, or objects. 我的用法适用于单个字符串,有打击的数组或对象。

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// loop through values in original array
for(i=0;i<max;i++){
    for(var val in legend){
            // looping through values in legend.  If match, convert
        if(old_array[i] === val){
            new_array[i] = legend[val];
        }
    }
}
console.log(new_array);
document.write(new_array);

If you paste that into firebug or jsfiddle, it'll show a new array with the converted values. 如果将其粘贴到firebug或jsfiddle中,它将显示带有转换后值的新数组。

I decided on object/associative array as my legend because it's easy to expand in case new values need to be converted. 我决定将对象/关联数组作为我的图例,因为在需要转换新值的情况下很容易扩展。 I think it's pretty robust. 我认为它非常强大。 And it works for converting an individual string, an array as shown above, or an object, either the keys or the values. 它适用于转换单个字符串,如上所示的数组或对象(键或值)。

For converting values, is it the best method? 对于转换值,这是最好的方法吗? Any considerations? 有什么考虑吗? For php, as it's the only other language I use regularly, would the same concept, with an associative array, also be used? 对于php来说,因为它是我经常使用的唯一其他语言,是否还会使用具有关联数组的相同概念?

Thanks so much for your help and advice! 非常感谢您的帮助和建议!

Cheers! 干杯!

You're not using the power of the object as there is no reason to loop through the object. 您没有使用对象的功能,因为没有理由遍历对象。 It already has keys that you can just lookup directly like this: 它已经具有可以直接像这样直接查找的键:

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// loop through values in original array
for(var i=0;i<max;i++){
    // see if array value is a key in the legend object
    if ([old_array[i] in legend) {
        new_array.push(legend[old_array[i]]);
    }
}
console.log(new_array);
document.write(new_array);

I also changed it to use new_array.push() so you don't end up with an array with some undefined values, but I'm not really sure what type of end result you're trying to end up with. 我也将其更改为使用new_array.push()因此您不会最终得到带有一些未定义值的数组,但是我不太确定要尝试使用哪种最终结果。

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

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