如何在javascript中动态添加属性?

时间:2015-10-03 16:50:28

标签: javascript object

我想知道每个字母表中有多少次输入'变量。为此我循环遍历每个角色并将它们存储在一个对象中,以及它们在句子中出现的数量。但它正在安慰NaN。请告诉我错误在哪里?

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;
    });
    console.log(object);
} 

3 个答案:

答案 0 :(得分:1)

您可以使用 public final void drawLine(int xStart, int yStart, final int xEnd, final int yEnd, final Color c) { // Variables declaration this.xStart = xStart; this.yStart = yStart; this.xEnd = xEnd; this.yEnd = yEnd; // Getting the PixelWriter from the Canvas this.pw = canvas.getGraphicsContext2D().getPixelWriter(); /** * TODO Bresenham Implementation */ final WritablePixelFormat<ByteBuffer> format = WritablePixelFormat.getByteBgraPreInstance(); double dx = xEnd - xStart; double dy = yEnd - yStart; double error=dx/2.0; byte imageData[] = new byte[300]; System.out.println("Red: "+c.getRed()+"\tGreen: "+c.getGreen()+"\tBlue: "+c.getBlue()); // R=0, G=0, B=0 (black) for ( int i = 0;i<100;i++) { int k = 0; imageData[i]=(byte) c.getRed(); imageData[i+1]=(byte) c.getGreen(); imageData[i+2]=(byte) c.getBlue(); k+=3; pw.setPixels(i, i, 1, 1, format,imageData, 0, 1); } 检查属性是否存在。

hasOwnProperty

对于仇敌,你可以初始化为1,只在else中增加。基本相同,但几个周期更有效。使用您认为最佳的选择。

var input = "why this kolaveri kolaveri di";


var object = {};
input.replace(/\s/g,"").split("").forEach(function(item){
  
  // If the property doesn't exist, initialize it to 0
  if (!object.hasOwnProperty(item))
    object[item] = 0;
  
  object[item]++
});
console.log(object);
 

答案 1 :(得分:0)

这项工作

  typeof object[item] == 'undefined' ?

答案 2 :(得分:0)

您在下面的代码行中遇到了问题。

object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;

更新代码:

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        if(object[item] == null)
        { 
            object[item] = 0;
            object[item]++; 
        }else{
            object[item]++;
        }
    });
    console.log(object);
}

//testing here 
processData(input);