JavaScript 循环遍历消息

3

我有3个变量中的信息。

var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";

我正在尝试创建一个函数,当我点击它时,第一次会console.log(msg1),第二次点击会console.log(msg2),第三次点击会console.log(msg3),第四次点击会console.log(msg1),第五次会console.log(msg2)等等。

$scope.clickMsg = function () {        
   console.log(msg1);
}

我尝试了循环、定时器等方法,但都无法使它工作。

有人知道怎么做吗?


为什么不使用数组? - Jonas Grumann
6个回答

6

使用数组代替,这样会更容易一些,你只需要在每次点击时增加一个数字,并使用该数字从数组中选择项目。

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>


1

基于 ES6 生成器 的版本:

var messages = (function*() { 
     for(;;) { yield msg1; yield msg2; yield msg3; } 
})()

$scope.clickMsg = function () {        
     console.log(messages.next().value);
}

与其他答案不同,它不需要您使用不同的数据类型,并且也适用于本地作用域变量(即非全局作用域变量)。

在线尝试!


0

只需像这样使用增量值即可

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++; 
}

Working snippet

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>


0

另一种选择是使用作用域,将它们定义为

  this["msg"+i] = "some stuff";

并将它们检索出来

this.msg0;

0

只需像这样做,就可以为您工作,确保在需要时将其重置回来或执行某些操作,否则在第一次循环后,您将得到未定义:

 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
   }
}

0

在访问字符串方面,有几种方法可供选择,我建议将它们放入数组中而不是访问全局/作用域对象,但这取决于您。无论如何,接下来是代码。

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接