Javascript动态字符串数组 [英] Javascript dynamic array of strings

查看:53
本文介绍了Javascript动态字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Javascript上创建动态字符串数组?
我的意思是,在一个页面上,用户可以输入一个数字或30个数字,然后他/她按下OK按钮,下一页按照输入的顺序显示数组,一个元素在一个时间。

Is there a way to create a dynamic array of strings on Javascript? What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.

感谢代码。

推荐答案


我的意思是,在页面上,用户可以输入一个数字或30个数字,然后他/她按下OK按钮,下一页按照输入的顺序显示数组,一次一个元素。

What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.

好的,所以你首先需要一些用户输入?有几种方法可以做到这一点。

Ok, so you need some user input first? There's a couple of methods of how to do that.


  1. 首先是提示符()显示弹出窗口的功能,询问用户输入的内容。


    • 优点:简单。缺点:难看,不能轻易回去编辑。

  1. First is the prompt() function which displays a popup asking the user for some input.
    • Pros: easy. Cons: ugly, can't go back to edit easily.

  • 优点:可以设置样式,用户可以轻松查看和编辑。缺点:需要更多编码。

对于提示方法,收集你的字符串很轻松:

For the prompt method, collecting your strings is a doddle:

var input = []; // initialise an empty array
var temp = '';
do {
    temp = prompt("Enter a number. Press cancel or leave empty to finish.");
    if (temp === "" || temp === null) {
        break;
    } else {
        input.push(temp);  // the array will dynamically grow
    }
} while (1);

(是的,这不是最漂亮的循环,但已经很晚了,我是累了....)

另一种方法需要更多努力。

The other method requires a bit more effort.


  1. 在页面上放置一个输入字段。

  2. 为其添加 onfocus 处理程序。

  1. Put a single input field on the page.
  2. Add an onfocus handler to it.

  1. 检查此后是否有另一个输入元素,如果有,请检查它是否为空。


    • 如果有,请不要做任何事情。

    • 否则,创建一个新输入,放在此之后一个并将相同的处理程序应用于新输入。


  • 当用户点击时好的,循环浏览页面上的所有< input> 并将它们存储到一个数组中。

  • When the user clicks OK, loop through all the <input>s on the page and store them into an array.
  • 例如:

    // if you put your dynamic text fields in a container it'll be easier to get them
    var inputs = document.getElementById('inputArea').getElementsByTagName('input');
    var input = [];
    for (var i = 0, l = inputs.length; i < l; ++i) {
        if (inputs[i].value.length) {
            input.push(inputs[i].value);
        }
    }
    

    之后,无论您收集输入的方法如何,您可以通过多种方式在屏幕上打印数字。一个简单的方法是这样的:

    After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:

    var div = document.createElement('div');
    for (var i = 0, l = input.length; i < l; ++i) {
        div.innerHTML += input[i] + "<br />";
    }
    document.body.appendChild(div);
    

    我把它放在一起所以你可以看到它在jsbin上工作

    提示方法: http://jsbin.com/amefu

    输入法: http://jsbin.com/iyoge

    这篇关于Javascript动态字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆