简体   繁体   中英

Convert string to JS object

I know its a repeated questions but I cannot figure out how to do in my case. I want to play audio using JS Buzz library. Please check following

var pg1 = new buzz.sound("oimages/music/as.mp3");
var pg2 = new buzz.sound("oimages/music/zx.mp3");
var pg3 = new buzz.sound("oimages/music/as.mp3");

On a certain event I want to play this audio. here 1, 2 and 3 are page numbers. Please check following

$("#flipbook").bind("turned", function (event, page, view) {;
    bog ='pg'+page; // page is the number of page here
    window.bog.play(); //error
});

It gives me following error

Uncaught TypeError: window.bog.play is not a function

Please guide.

Simple mistake. You're trying to reference the variable incorrectly. bog isn't the name, but it contains the name...

$("#flipbook").bind("turned", function (event, page, view) {;
    bog ='pg'+page; // page is the number of page here
    window[bog]play(); //error
});

This assumes that the pg1..3 variables have global scope. If they don't then change the declarations to...

window.pg1 = new buzz.sound("oimages/music/as.mp3");

etc..

Because bog ='pg'+page; is a string, not a reference to the sound file.

You need to reference the sound assuming they are in global scope you can use bracket notation

var bog = window['pg'+page];

Evaluating would do the trick:

$("#flipbook").bind("turned", function (event, page, view) {;
    bog ='pg'+page;
    eval('window.' + bog + '.play()');
});

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