gpt4 book ai didi

javascript - 将重复代码注入(inject)函数 : JavaScript

转载 作者:行者123 更新时间:2023-11-30 15:04:45 24 4
gpt4 key购买 nike

下面的add8 函数内部有很多for 循环。为了这个问题的目的,我已经 chop 了它,但是我的源代码中的原始函数中有更多的循环。看看:

function select( selector ){
return document.querySelectorAll( selector );
}

function add8(){
var x = select( '[ x ]' ), y = select( '[ y ]' ),
x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
i = 0,
val = 0;

for( i = 0; i < x.length; i++ ){
val = x[ i ].getAttribute( 'x' );
val = Number( val ) + 8;
x[ i ].setAttribute( 'x', val );
}
for( i = 0; i < y.length; i++ ){
val = y[ i ].getAttribute( 'y' );
val = Number( val ) + 8;
y[ i ].setAttribute( 'y', val );
}
for( i = 0; i < x1.length; i++ ){
val = x1[ i ].getAttribute( 'x1' );
val = Number( val ) + 8;
x1[ i ].setAttribute( 'x1', val );
}
for( i = 0; i < y1.length; i++ ){
val = y1[ i ].getAttribute( 'y1' );
val = Number( val ) + 8;
y1[ i ].setAttribute( 'y1', val );
}
// Alot more 'for' loops follow...
}

add8();

您可能会注意到,在这些 for 循环中只有少数几个值需要更改,因此我迫切需要一个可以重用大量代码同时使整体代码更短和简洁的函数。

有点像

function dynamicFunc( dynamicVar, dynamicStr ) {
for( i = 0; i < dynamicVar.length; i++ ){
val = dynamicVar[ i ].getAttribute( dynamicStr );
val = Number( val ) + 8;
dynamicVar[ i ].setAttribute( dynamicStr, val );
}
}

function add8(){
var x = select( '[ x ]' ), y = select( '[ y ]' ),
x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
i = 0,
val = 0;

dynamicFunc( x, 'x' );
dynamicFunc( y, 'y' );
dynamicFunc( x1, 'x1' );
dynamicFunc( y1, 'y1' );

// Alot more follow...
}

add8();

自动执行那些 for 循环,但下面的示例似乎不起作用。我还不太擅长 JS,我想我需要一点帮助。我怎样才能做到这一点?谢谢。

注意:我在源代码中处理大量 SVG,因此属性 xyx1 等...在我的 JavaScript 中被选中。

额外注意:我在这里使用 vanilla JS。

最佳答案

使用一些 ES6 特性:

function add8(){
var attributes = ['x', 'y', 'x1', 'y1']; // all the attributes you care about
attributes.forEach(attribute => {
[...select(`[${attribute}]`)].forEach(el => {
el.setAttribute(attribute, Number(el.getAttribute(attribute)) + 8);
});
});
}

更详细:

function add8(){
var attributes = ['x', 'y', 'x1', 'y1']; // all the attributes you care about
var i, j;
// loop over the attributes:
for (i = 0; i < attributes.length; i++) {
var attribute = attributes[i];
var elements = select('[' + attribute + ']');
// loop over the selected elements:
for (j = 0; j < elements.length; j++) {
var element = elements[i];
var val = Number(el.getAttribute(attribute)) + 8;
el.setAttribute(attribute, val);
}
}
}

关于javascript - 将重复代码注入(inject)函数 : JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com