我在JavaScript中有一个构造函数,如下所示,并希望从数组中提供构造函数参数:
na.rm = TRUE
现在我想要从数组提供的构造函数参数:
function dataRow(value1, value2, value3, value4, value5) {
this.val1 = value1;
this.val2 = value2;
this.val3= value3;
this.val4 = value4;
this.val5 = value5;
}
我希望(value1,value2,value3,value4,value5)此部分从我的var dataArray = new Array();
dataArray("Value1","Value2","Value3","Value4","Value5","Value6"...........)
填充。
答案 0 :(得分:2)
在现代环境中,您可以使用spread notation:
// CustomerSelect.js
import React from "react";
import { Field } from "redux-form";
import Grid from "material-ui/Grid";
import renderAsyncCreatableSelect from "../redux-form-connectors/renderAsyncCreatableSelect";
const CustomerSelect = ({ customers, selectedCustomer }) => {
// customers: [{name: "Alice", _id: "$7637221n...}, ...]
const options = customers.map(customer => ({
label: customer,
value: customer
}));
return (
<Grid item>
<Field
name="customer"
component={renderAsyncCreatableSelect}
label="Customer"
selectedValue={selectedCustomer}
/>
</Grid>
);
};
// renderAsyncCreatableSelect.js
import React, { Component } from "react";
import axios from "axios";
import AsyncCreatableSelect from "react-select/lib/AsyncCreatable";
const getOptions = () => {
return axios
.get("/api/customers") // [{_id: "", name: "", user: ""... }, ...]
.then(res => res.data.map(el => ({ label: el.name, value: el._id })));
};
export default class renderAsyncCreatableSelect extends Component {
onChange = (event) => {
if (this.props.input.onChange && event != null) {
this.props.input.onChange(event.value);
} else {
this.props.input.onChange(null);
}
};
render() {
const { input, selectedValue } = this.props;
return (
<AsyncCreatableSelect
cacheOptions
defaultOptions
placeholder={"Customer..."}
loadOptions={getOptions}
value={input.value ? input.value : selectedValue.label}
onBlur={() => input.onBlur(input.value)}
onChange={this.onChange}
/>
);
}
}
var row = new dataRow(...dataArray);
&#13;
在旧环境中,这样做真的很痛苦。在您的具体情况下,可能只是这样做:
function dataRow(v1, v2, v3, v4, v5) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
this.v5 = v5;
}
var dataArray = [1, 2, 3, 4, 5];
var row = new dataRow(...dataArray);
console.log(row.v1);
console.log(row.v2);
console.log(row.v3);
console.log(row.v4);
console.log(row.v5);
或者您可以将创建与通话分开,并使用Function#apply
:
dataRow(dataArray[0], dataArray[1], dataArray[2], dataArray[3], dataArray[4]);
var row = Object.create(dataRow.prototype);
dataRow.apply(row, dataArray);
&#13;
这不适用于通过function dataRow(v1, v2, v3, v4, v5) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
this.v5 = v5;
}
var dataArray = [1, 2, 3, 4, 5];
var row = Object.create(dataRow.prototype);
dataRow.apply(row, dataArray);
console.log(row.v1);
console.log(row.v2);
console.log(row.v3);
console.log(row.v4);
console.log(row.v5);
创建的构造函数,但如果您通过class
创建它,请使用扩展表示法;它们是同时推出的(ES2015)。
我建议不这样做,特别是考虑到your comment below:
...如何动态创建this.val1 = value1; this.val2 = value2; this.val3 = value3; ...
相反,使用单个数组属性,并传入一个您保留或复制的数组:
class
&#13;