我有java的背景,与javascript打交道并不是一件令人愉快的事情。我想写一个函数,它接收一个二维点(x,y)数组,并再次返回另一个二维点数组。在Java语言中,我可以定义类,比如C2DPoints,并在我的函数定义中像在输入参数类型中一样使用,也可以作为输出类型使用。但是,在javascript中处理这个问题的最佳方法是什么?
我的解决方案是:
function scale2D(x,y, scaleX, scaleY){
// primitives x, y are passed by value
for (i=0;i< x.length;i++){
x[i] = x[i]*scaleX;
y[i] = y[i]*scaleY;
}
return [x,y];
}
发布于 2014-01-01 02:28:41
有很多方法..。在jsfiddle中尝试一些东西。
//Taking in 2 numbers
var newArr = function(x,y){
var a = x+1,
b = y+1;
return [a,b];
}
console.log(newArr(1,1));
// Will echo: [2,2]
//Taking in an array of 2 numbers
var newArr = function(x){
var a = x[0]+1,
b = x[1]+1;
return [a,b];
}
console.log(newArr([1,1]));
// Will echo: [2,2]
// Taking in an object
var newArr = function(obj){
var a = obj.x+1,
b = obj.y+1;
return [a,b];
}
console.log( newArr({x:1,y:1}) );
// Will echo: [2,2]
// Accept an Obj and return an Obj
var newArr = function(obj){
var a = obj.x+1,
b = obj.y+1;
return {a:a,b:b};
}
console.log( newArr({x:1,y:1}) );
// Will echo: {a:2,b:2}
发布于 2014-01-01 02:21:27
当然,请查看JavaScript对象文字表示法。实际上,您甚至不必在JavaScript中创建类,您可以在函数中创建对象,并在构造过程中为它们提供您想要的函数。
function main() {
var myGuy = returner();
myGuy.sayAge();
}
function returner() {
return {
name: "bob",
age: "99",
sex: "m",
sayAge: function() {
console.log(this.age);
}
};
}
但是,就您的示例而言,您仍然可以继续采用OOP方法,并创建一种Point类。
function main() {
var points = [];
for (var i = 0; i < 10; i++) {
points.push(new Point2D(i, i + 1));
}
manipArray(points);
for (var i = 0; i < 10; i++) {
console.log("Point: " + i + " x: " + points[i].x + " y: " + points[i].y);
}
}
function Point2D(x, y) {
this.x = x;
this.y = y;
}
Point2D.prototype.add = function(other) {
this.x += other.x;
this.y += other.y;
}
function manipArray(arrOfPoints) {
var myPoint = new Point2D(4, 5);
for (var i = 0; i < arrOfPoints.length; i++) {
arrOfPoints[i].add(myPoint);
}
}
当main()
运行时,它将为您提供:
Point: 0 x: 4 y: 6 (12:48:07:947)
Point: 1 x: 5 y: 7 (12:48:07:952)
Point: 2 x: 6 y: 8 (12:48:07:956)
Point: 3 x: 7 y: 9 (12:48:07:958)
Point: 4 x: 8 y: 10 (12:48:07:959)
Point: 5 x: 9 y: 11 (12:48:07:961)
Point: 6 x: 10 y: 12 (12:48:07:962)
Point: 7 x: 11 y: 13 (12:48:07:963)
Point: 8 x: 12 y: 14 (12:48:07:964)
Point: 9 x: 13 y: 15 (12:48:07:965)
这意味着您传递的点已经作为排序的out
参数在函数中进行了更改。这就是你要找的东西吗?
发布于 2014-01-03 09:43:34
//Taking in 2 numbers as an Object
const newArr = function(x,y){
this.x = x+1,
this.y = y+2;
},
const Arr = new newArr(1,1);
console.log(Arr.x);
// Will echo: 2
console.log(Arr.y);
// Will echo: 3
https://stackoverflow.com/questions/20861637
复制相似问题