【问题标题】:javascript loop through messagesjavascript循环遍历消息
【发布时间】:2017-09-30 02:20:10
【问题描述】:
我在变量中有 3 条消息。
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
我正在尝试创建一个函数,当我第一次单击它时它是 console.log(msg1),当我第二次单击它时它是 console.log(msg2),第三次是 console.log(msg3),第 4 次 console.log(msg1) 和第 5 次 msg2 等等。
$scope.clickMsg = function () {
console.log(msg1);
}
我尝试过循环、计时器等,但我无法让它工作。
有人知道怎么做吗?
【问题讨论】:
标签:
javascript
angularjs
loops
【解决方案1】:
使用数组来代替,它更容易一点,您只需在每次点击时增加一个数字,然后使用该数字从数组中选择项目
var msg = [
"hello1",
"hello2",
"hello3"
];
var i = 0;
var $scope = {};
$scope.clickMsg = function () {
console.log( msg[i] );
i++; // increment
if (i === msg.length) i = 0; // reset when end is reached
}
document.getElementById('test').addEventListener('click', $scope.clickMsg)
<button id="test">Click</button>
【解决方案2】:
基于 ES6 Generators 的版本:
var messages = (function*() {
for(;;) { yield msg1; yield msg2; yield msg3; }
})()
$scope.clickMsg = function () {
console.log(messages.next().value);
}
与其他答案不同,它不需要您使用不同的数据类型,并且也适用于本地范围的变量(即非窗口范围的变量)。
Try It Online !
【解决方案3】:
在访问字符串方面有几种方法可以做到这一点,我建议将它们放入数组而不是访问全局/范围对象,但这取决于您。无论如何,继续代码。
var messagesArray = ["hello1", "hello2", "hello3"];
var messagesObject = {
msg1: "hello1",
msg2: "hello2",
msg3: "hello3"
}
var counter = 0;
function LogMessage() {
console.log(messagesArray[counter % 3]);
console.log(messagesObject["msg" + (counter % 3 + 1)]);
counter++
}
<button onclick="LogMessage()">Click Me</button>
【解决方案4】:
像这样简单地使用增量值
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
var c = 1;
$scope.clickMsg = function () {
c = c > 3 ? 1 : c;
console.log(window['msg'+c])
c++;
}
工作 sn-p
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
var c = 1;
var $scope={} //for testing
$scope.clickMsg = function () {
c = c > 3 ? 1 : c;
console.log(window['msg'+c])
c++;
}
function check(){ //for testing
$scope.clickMsg();
}
<button onclick="check()">click</button>
【解决方案5】:
另一种方法是使用范围,将它们定义为
this["msg"+i] = "some stuff";
并将它们检索为
this.msg0;
【解决方案6】:
只要做这样的事情,对你有用,确保你在需要时重置它或做一些事情,否则在第一次循环之后,你会得到未定义:
var msgs = ["hello1","hello2","hello3"], i=0;
$scope.clickMsg = function() { //angular $scope for example
console.log(msgs[i]);
if(i < msgs.length-1) {
i++;
} else {
i=0; //reset the loop
}
}