使用变量强制对象属性以重新计算值

时间:2017-07-14 20:04:33

标签: javascript jquery object dom audio

我有一个带有属性的对象,该属性通过Howler.js库加载声音样本。

样本路径的一部分是通过模式变量确定的,模式变量可以是A,B,C等所有有效文件夹,包含具有相同名称但声音略有不同的声音样本。

var mode = "A";
$("html").on("keydown", function(e){
    if(e.keyCode === 32) {
        switch (mode) {
            case "A":
                mode = "B";
                break;
            case "B":
                mode = "C";
                break;
            .
            .
            .
            default:
                mode = "A";
        }
    }

    dict["coolSound"].sound.play();
});



// Seperate file
var dictionary = {
    coolSound: {
               sound: new Howl({
                   src: ["sounds/" + mode + "/bubbles.mp3"]
               })
};

使用按键,我将模式变量更改为下一个字母。 但是,播放的声音是原始声音。

我试图让它调用一个设置声音的功能,但这也不起作用。

我在主词典对象中有多个这样的对象和属性。有没有办法更新属性而无需手动循环它们?

1 个答案:

答案 0 :(得分:0)

不,您在代码开头设置的属性只是一个字符串,它不记得它是由字符串,变量和字符串组成的。

您可以使用函数而不是字符串值。例如:

dict["coolSound"].sound(mode).play();

然后,在您的keydown处理程序中,您可以执行以下操作:

const users = [
  {
    "login": "norvig",
    "firstName": "Peter",
    "lastName": "Norvig",
    "likes": ["AI", "Search", "NASA", "Mars"]
  }
];

// lookupAsync()
const lookupAsync = (login, prop, callback) => {

// Only change code below this line


    const found = users.find(function(e) {
      return e.login === login;
    });

    if (!found) {
      throw "Could not find user.";
    } else {
      if (prop in found) {
        return found[prop];
    } else {
        throw "Could not find property";
      }
    }


//my current concept according to suggestion but trying to set in the     
code.

function mycallback(callback) {
var err,res;
callback(err,res);
}
mycallback( function() {
console.log();
});

};

test('lookupAsync() likes', assert => {
  const msg = `lookupAsync(<login>, 'likes', callback) should return         

  likes for the specified user.`;

  lookupAsync('norvig', 'likes', function(err, res){
    const actual = res;
    const expected = ["AI", "Search", "NASA", "Mars"];
    assert.deepEqual(actual, expected, msg);
    assert.end();     
  });

});
test('lookupAsync() with unknown user', assert => {
const msg = `lookupAsync() with unknown user should return an error
with the correct message.`;

const value = lookupAsync('nobody', 'likes', function(err, res){
const actual = err.message;
const expected = 'Could not find user.';
assert.equal(actual, expected, msg);
assert.end();  
});
});