是否可以通过循环数组来填充Object实例?

时间:2016-09-29 19:24:43

标签: javascript arrays javascript-objects

我正在创建一个日记应用,并且每次在我的html表单上提交输入时都需要创建一个对象实例。

我想创建一个循环,它接受结果中的输入并将它们转换为新Object实例中的值。到目前为止,我对此的尝试为我提供了一个具有未定义值的实例。这甚至可以吗?

results = []

function example(a, b){
    this.a = a;
    this.b = b;
}

function getElements(){
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
results.push(a,b)
}

我尝试在循环中创建示例

的新实例
function createNewDay(){
    for (i = 0;i<results.length;i++){
    var x = new day([i])
    }
}

当我在console.log =&gt;示例{a:undefined,b:undefined}

3 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input id="a" type="text">
  <input id="b" type="text">
  <button type="submit" id="submit">Submit</button>
  <button type="button" id="view">View results in console</button>
</body>
<script type="text/javascript">
var results = [];

function Example(a, b) {a
  this.a = a;
  this.b = b;
}

function getElements() {
 var a = document.getElementById('a').value;
 var b = document.getElementById('b').value;
 results.push(new Example(a, b));
}

function loopResults() {
  for (var i = 0; i < results.length; i++) {
    console.log(results[i]);
  }
}

document.getElementById('submit').addEventListener('click', getElements, false);
document.getElementById('view').addEventListener('click', loopResults, false);
</script>
</html>

演示:http://jsbin.com/jehupayomu/1/

答案 1 :(得分:0)

所以...你可以使用jquery:

var formDataObject = $("refer_to_form_by_id_or_name").serializeObject();

如此处所述:Serialize form data to JSON

答案 2 :(得分:0)

您可以使用View cachingView = getActivity().getWindow().getDecorView().getRootView(); cachingView.setDrawingCacheEnabled(true); cachingView.setLayerType(View.LAYER_TYPE_NONE,null); cachingView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW); Bitmap bitmap = Bitmap.createBitmap(cachingView.getDrawingCache()); LogHelper.i("bitmap size: "+bitmap.getByteCount()); LogHelper.i("bitmap size: "+ BitmapCompat.getAllocationByteCount(bitmap)); - 这使其成为更通用的解决方案:

&#13;
&#13;
FormData
&#13;
var form = document.querySelector('form');

form.onsubmit = function () {
    var formdata = new FormData(this);
    var results = {};
    for ([key, value] of formdata) {
        results[key] = value;
    }
    console.log(results);
    return false; // cancel submission
};
&#13;
&#13;
&#13;