如何从DOM中检索值拆分数组 [英] How to split an array with retrieved values from DOM

查看:196
本文介绍了如何从DOM中检索值拆分数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从一个表,从一列始发检索到的值,即我最终存储在数组中;但所有的数据存储在一个单一的索引,并且我还没有成功地与.split分裂阵列

I've retrieved values from a table, originating from a single column, that I end up storing in an array; but all the data is stored in a single index, and I haven't succeeded in splitting the array with .split.

第1步 - 我的目标体和TR

Step 1 -- I target body and tr.

var stuff = document.getElementById('pricetable').querySelectorAll('tbody tr');

步骤2 - 我发起一个for循环

Step 2 -- I initiate a for-loop:

for (var i = 0; i < rows.length-1; i++) {
        var rows2 = Array.prototype.slice.call(stuff)[i].querySelectorAll('td')[3];}

rows2现在将打印一个字符串,看起来像这样:

rows2 will now print a string that looks like this:

<td>​2400​</td>​ 
<td>​1900​</td>​
<td>​9790​</td>​
<td>​1098​</td>​
<td>​1289​</td>​
<td>​3284​</td>​

我想我的问题从这里开始,因为我不知道如何将它做成一个数组,并有每个值存储在其自己的索引。

I think my problem starts here, since I don't know how to make it into an array and have each of these values stored its own index.

第3步 - 要检索只有文字,我创建了一个新的变量:

Step 3 -- To retrieve only the text, I create a new variable:

var my_list = rows2.textContent;    

第4步 - 然后我试图分裂数组:

Step 4 -- I then attempt to split the array:

var price_list = my_list.split(','));

虽然PRICE_LIST是一个数组(我验证),所有值保持在PRICE_LIST [0]。它打印这样的:

Although price_list is an array (I verified), all values remain in price_list[0]. It prints like this:

["2400"]
["1900"]
["9790"]
["1098"]
["1289"]
["3284"]

如果拆分不会做的伎俩在这种情况下,我需要遍历这些价值观?如果是这样,怎么样?或者我应该采取行动不同的课程?我已经做了研究解释了如何分割与不是从DOM中检索predefined字符串工作。

If split won't do the trick in this case, do I need to loop through those values? If so, how? Or should I have taken a different course of action? The research that I've done explains how split works with predefined strings that aren't retrieved from the DOM.

推荐答案

首先,这是完全没有必要的......

First, this is completely unnecessary...

var rows2 = Array.prototype.slice.call(stuff)[i].querySelectorAll('td')[3];

另外,你的变量命名是怪异。你为什么叫它 rows2 当你得到第4单元?

要获得第四小区,只是这样做:

To get the fourth cell, just do this:

var cell4 = stuff[i].cells[3]; 


但是,如果你希望这些值的数组,然后做这个吧。


But if you want an array of those values, then do this instead.

var list = Array.prototype.map.call(stuff, function(row) {
    return row.cells[3].textContent;
});

此借用 Array.prototype .MAP()功能,它给你的一个新的数组什么值从回调返回。

This borrows the .map() function from Array.prototype, which gives you a new array of whatever values you returned from the callback.

如果这不是你想要的,那么你就需要来形容,那就是你之后,而不是仅仅显示code你想要什么,不办是具体是什么。

If this isn't what you want, then you need to describe specifically what it is you're after instead of just showing code that doesn't do what you want.

这篇关于如何从DOM中检索值拆分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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